//
//  CollectionViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/9.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "CollectionViewController.h"
#import "ZLDetailPoemViewController.h"
#define COLLECTED_POEM_PATH NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject

static NSString *const kUITableViewCellIdentifier = @"collectCellIdentifier";

@interface CollectionViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating> {
    NSMutableArray *_collectionDataSource;
    NSString *_collectedPoemPath;
}

@property (nonatomic, strong) UISearchController * searchController;
@property (nonatomic, strong) UITableView * collectionTabView;
@property (nonatomic, strong) NSMutableArray * searchResult;
@property (nonatomic, assign) BOOL isSearch;
- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */

@end

@implementation CollectionViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self initializeDataSource];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
    
}

#pragma mark - private methods
- (void)initializeDataSource {
    _isSearch = NO;
    // 将搜索栏是否隐藏置为NO。
    self.searchController.searchBar.hidden = NO;
    // 将搜索控制器是否活动置为NO。
    self.searchController.active = NO;
    _collectedPoemPath = [COLLECTED_POEM_PATH stringByAppendingString:@"/CollectedPoem.plist"];
    _collectionDataSource = [NSMutableArray arrayWithContentsOfFile:_collectedPoemPath];
    [self.collectionTabView reloadData];
    if (_collectionDataSource.count == 0) {
        [self.searchController.searchBar removeFromSuperview];
        [self initializeAlertControllerWithMessage:@"您尚未收藏喜欢的诗"];
        
    }
}
- (void)initializeUserInterface {
    CALayer *layer = [CALayer layer];
    layer.bounds = self.view.bounds;
    layer.position = self.view.center;
    layer.contents = (__bridge id)(IMAGE_CONTENT(@"帮助背景图.png")).CGImage;
    [self.view.layer addSublayer:layer];
    self.titleLable.text = @"收藏";
    [self.baseNavigationBar removeFromSuperview];
    [self.view addSubview:self.baseNavigationBar];
    [self.view addSubview:self.collectionTabView];
    
}
#pragma mark - responds events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //收起键盘点击其他地方
    [self.view endEditing:YES];
    [self.collectionTabView endEditing:YES];
}
#pragma mark---协议UITableViewDelegate
- (NSArray*)visibleCells
{
    return [self.collectionTabView visibleCells];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _isSearch ?self.searchResult.count: _collectionDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!_isSearch) {
        cell.textLabel.text = _collectionDataSource[indexPath.row][@"title"];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@·%@", _collectionDataSource[indexPath.row][@"zuozhe"],  _collectionDataSource[indexPath.row][@"chaodai"]];
    } else {
        cell.textLabel.text = self.searchResult[indexPath.row][@"title"];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@·%@", self.searchResult[indexPath.row][@"zuozhe"], self.searchResult[indexPath.row][@"chaodai"]];
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
#pragma mark - UITableViewDataSource
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZLDetailPoemViewController * detailVC = [[ZLDetailPoemViewController alloc]init];
    detailVC.poemDic = _collectionDataSource[indexPath.row];
    detailVC.poemArray = _collectionDataSource;
    [self.navigationController pushViewController:detailVC animated:YES];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (!searchController.active) {
        _isSearch = NO;
        [self.collectionTabView reloadData];
        return;
    }
    _isSearch = YES;
    NSString * findString = searchController.searchBar.text;
    self.searchResult = [NSMutableArray new];
    for (NSDictionary * dict in _collectionDataSource) {
        if ([dict[@"title"] containsString:findString]|[dict[@"zuozhe"] containsString:findString]) {
            [self.searchResult addObject:dict];
        }
    }
    [self.collectionTabView reloadData];
}
#pragma mark - getter
- (UISearchController *)searchController {
    if (!_searchController) {
        _searchController = ({
            UISearchController * searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
            searchVC.searchBar.frame = DHFlexibleFrame(CGRectMake(0, 0, 320, 40), YES);
            searchVC.hidesNavigationBarDuringPresentation = NO;
            searchVC.dimsBackgroundDuringPresentation = NO;
            searchVC.searchBar.placeholder = @"请输入作品名或者作者名搜索";
            searchVC.searchBar.backgroundImage = IMAGE_CONTENT(@"帮助背景图.png");
            searchVC.searchResultsUpdater = self;
            searchVC;
        });
    }
    return _searchController;
}
- (UITableView *)collectionTabView {
    if (!_collectionTabView) {
        _collectionTabView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(0, 55, ORIGIN_WIDTH, ORIGIN_HEIGHT- 55), NO) style:UITableViewStylePlain];
            tableview.separatorColor = ZLColor(48, 121, 33);
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.bounces = NO;
            tableview.backgroundColor = [UIColor clearColor];
            tableview.tableHeaderView = self.searchController.searchBar;
            tableview;
        });
    }
    return _collectionTabView;
}
@end
